package com.thomas.tool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.thomas.model.ImageModel;

/**
 * @author Thomas
 * 图片操作的工具类
 *
 */
public class ImageUtil {
	
	// Utility classes should not have a public constructor
	private ImageUtil() {}
	
	private static int errorCount = 0;
	
	/**
	 * 根据图片的 model 保存图片到硬盘
	 * @param imageModel
	 * @return
	 */
	public static boolean saveImageByImageModel(ImageModel imageModel) {
	
		InputStream in   = null;
		OutputStream out = null;
		
		String imageUrl = imageModel.getImageUrl();
		String imageName = imageModel.getImageName();
		String imageFolder = imageModel.getImageFolder();
		
		try {
			
			URL url = new URL(imageUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setRequestMethod("GET");
			conn.setRequestProperty("User-agent","Mozilla /23.451");
			conn.setReadTimeout(15000);
			if(conn.getResponseCode() != 200) {
				System.out.println(imageName + " fail ! ");
				return false;
			}
			
			in = conn.getInputStream();
			
			File toSaveFile = new File(imageFolder);
			if (!toSaveFile.exists()) {
				toSaveFile.mkdir();
			}
			
			out = new FileOutputStream(imageFolder + "/" + imageName);
			int len = 0;
			byte[] data = new byte[1024];
			while((len=in.read(data)) != -1) {
				out.write(data, 0, len);
			}
		} catch (Exception e) {
			System.out.println("-----------------------------");
			System.out.print("exception..." + imageName);
			System.out.println(++errorCount);
			System.out.println("-----------------------------");
		}
		System.out.println(imageName + " saved ! ");
		return true;
	}
	
}





